package cn.alusiaor.eurekaclientarticleservice.config;

import cn.alusiaor.commonutil.JackJsonUtils;
import cn.alusiaor.eurekaclientarticleservice.response.CommonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author zhuzhiping
 * @description 统一返回结果配置
 * @date 2021/2/4 11:08
 */

@RestControllerAdvice
public class GlobalResponseResultConfig implements ResponseBodyAdvice<Object> {


    /**
     * 判断执行beforeBodyWrite的接口
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    /**
     * 包装返回的对象
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (Objects.isNull(body)) {
            return null;
        }
        if (body instanceof CommonResult) {
            return body;
        }
        CommonResult<Object> responseResult = new CommonResult<>(body);
        return (body instanceof String ? JackJsonUtils.obj2String(responseResult) : responseResult);
    }
}
